﻿var encounterID;

$(document).ready(function () {

    $("#btnSaveVitals").click(function () {
       saveVitals();
    });

    $("#lnkAddVitals").click(function () {
        toggleAddVitals()
    });

    encounterID = $("#vitalsList").data("encounterid");
    getVitals();
});

function toggleAddVitals() {
    var link = $("#lnkAddVitals");
    link.text() == "+ Add Vitals" ? link.text("- Hide Add Vitals") : link.text("+ Add Vitals");

    $("#addVitals").slideToggle();
}

function getVitals() {

    var url = 'Encounter/GetEncounterVitals';

    $.ajax({
        url: url,
        data: { encounterID: encounterID },
        type: 'post',
        dataType: 'json',
        success: function (data) {
            var vitalEncounters = JSON.parse(data);
            if (vitalEncounters != null && vitalEncounters.length > 0) {
                $("#vitals").show();
                $("#lnkAddVitals").text("+ Add Vitals");
                $("#addVitals").slideUp();
                $(vitalEncounters).each(function (index) {
                    var tr = "<tr><td>" + this.VitalName + "</td><td>" + this.VitalValue + "</td><td>" + formatJsonDate(this.CreatedDate) + "</td></tr>";
                    $("#tblVitals tbody").append(tr);
                });
            }
            else {
                $("#vitals").hide();
                $("#lnkAddVitals").text("- Hide Add Vitals");
                $("#addVitals").slideToggle();
            }
        },
        error: function (data) {
            alert("One of them there vitals didn't make it acrost...");
        }
    });


}

function showAddVitals() {
    if ($("#addVitals")) {
        $("#addVitals").slideToggle();
    }
    else {
        $("#addVitals").slideToggle();
    }

}


function saveVitals() {

    var vitals = [];

    $("#vitalsList input").each(function () {
        var vitalValue = $("#" + this.id).val();
        if(vitalValue != "")
        {
            var vital = { EncounterID: encounterID, VitalID: $(this).data("vitalid"), VitalValue: vitalValue };
            vitals.push(vital);
        }
    });

    var vitalsJSON = JSON.stringify(vitals);

    var url = 'Encounter/SaveAllEncounterVitals';

    $.ajax({
        url: url,
        data: { vitalsJSON: vitalsJSON },
        type: 'post',
        dataType: 'json',
        success: function (data) {
            var x = data;
            //todo: update vitals data for encounter page
            alert("All those vitals twere saved!");
        },
        error: function (data) {
            alert("One of them there vitals didn't make it acrost...");
        }
    });
   

}